package com.bhkj.pdjhforotherapp.core.main.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bhkj.pdjhforotherapp.R;
import com.bhkj.pdjhforotherapp.common.Contact;
import com.bhkj.pdjhforotherapp.common.utils.UpdateUtil;
import com.bhkj.pdjhforotherapp.common.view.ShadowDrawable;
import com.bhkj.pdjhforotherapp.core.base.BaseActivity;
import com.bhkj.pdjhforotherapp.core.jhaudio.AudioReceiver;
import com.bhkj.pdjhforotherapp.core.jhaudio.JhAudioService;
import com.bhkj.pdjhforotherapp.core.main.handler.MainYwHandler;
import com.bhkj.pdjhforotherapp.core.printutilspjq.PrintManagerPjq;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.example.reader.sdk.CardReader;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class MainYwActivity extends BaseActivity implements View.OnClickListener {
    RecyclerView mRv;
    private TextView mTvTime;
    private TextView mTvVehicleYw;
    private TextView mTvVehicleMan, mTvClearAll, mTvPickNum, mTvVipNum, mTvDeptName;
    private Badge mBadgeVehicleYw;
    private Badge mBadgeVehicleMan;
    private MainYwHandler mainYwHandler;
    private ConstraintLayout mClRootView;
    private ImageView mIvIcon;
    private AudioReceiver audioReceiver;

    @Override
    public int getLayoutId() {
//        ServiceUtils.startService(JhAudioService.class);
        return getResources().getBoolean(R.bool.isQhj) ? R.layout.activity_main_yw : R.layout.activity_main_yw_pjq;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        ServiceUtils.startService(JhAudioService.class);
        if (mainYwHandler != null && mainYwHandler.getMainYwAdapter() != null) {
            mainYwHandler.getMainYwAdapter().notifyDataSetChanged();
        }
    }

//
//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        if (mainYwHandler != null && ObjectUtils.isNotEmpty(mainYwHandler.getYwDataFromCache())) {
//            mainYwHandler.getMainYwAdapter().setNewData(mainYwHandler.getYwDataFromCache());
//        }
//    }


    @Override
    public void initView() {
        UpdateUtil.checkUpdate(this, true);
        mClRootView = findViewById(R.id.cl_main_yw_layout);
        mTvDeptName = findViewById(R.id.tv_main_yw_name);

        mTvClearAll = findViewById(R.id.tv_selected_yw_clear_all);
        mTvPickNum = findViewById(R.id.bt_selected_yw_picknum);
        mTvVipNum = findViewById(R.id.bt_selected_yw_vip_pick);

        mTvClearAll.setOnClickListener(this);
        mTvPickNum.setOnClickListener(this);
        mTvVipNum.setOnClickListener(this);

        mRv = findViewById(R.id.rv_main_yw_list);
        mTvVehicleYw = findViewById(R.id.tv_main_vehicle_yw);
        mTvVehicleYw.setOnClickListener(this);
        mTvVehicleMan = findViewById(R.id.tv_main_vehicle_man_yw);
        mTvVehicleMan.setOnClickListener(this);

        mIvIcon = findViewById(R.id.iv_main_yw_logo);
        mIvIcon.setOnClickListener(this);
        //机动车业务选中状态
        mBadgeVehicleYw = new QBadgeView(this).setBadgeText(getString(R.string.selected_title)).bindTarget(mTvVehicleYw);

        //驾驶人业务选中状态
        mBadgeVehicleMan = new QBadgeView(this).setBadgeText(getString(R.string.selected_title)).bindTarget(mTvVehicleMan);
        mBadgeVehicleMan.hide(true);

        //顶部渐变颜色
        View viewTop = findViewById(R.id.divider_top);
        ShadowDrawable.setShadowDrawable(viewTop, new int[]{
                        Color.parseColor("#536DFE"), Color.parseColor("#7C4DFF")}, SizeUtils.dp2px(1),
                Color.parseColor("#997C4DFF"), SizeUtils.dp2px(1), SizeUtils.dp2px(1), SizeUtils.dp2px(1));
        mTvTime = findViewById(R.id.tv_main_yw_time);
        mainYwHandler = new MainYwHandler();
        mainYwHandler.setBottomButtonColor(mTvPickNum, mTvClearAll, mTvVipNum);
        if (!getResources().getBoolean(R.bool.isQhj)) {
            final TextView tvShutDown = findViewById(R.id.bt_main_yw_shutdown);
            mainYwHandler.setShutDownColor(tvShutDown);
            tvShutDown.setOnClickListener(v -> mainYwHandler.shutDown());
        }
    }

    @Override
    public void initData() {
        if (audioReceiver == null) {
            audioReceiver = new AudioReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(audioReceiver, intentFilter);

//        ServiceUtils.startService(JhAudioService.class);

        if (!getResources().getBoolean(R.bool.isQhj)) {
            PrintManagerPjq.getInstance().registerBroadcast(this);
            PrintManagerPjq.getInstance().connectPrintDevice();
        } else {
            initReadIdCard();
        }
        mainYwHandler.setButtonWithJBColor(true);
        initTime();
    }

    private void initReadIdCard() {
        CardReader.getInstance(getApplication()).init(readerBean -> {
            LogUtils.d("读卡器:" + readerBean.getMessage());
        });
//        IDCardReaderManager.getInstance().setDeviceType(Contacts.USB_MODE).init(tip -> {
//            if (!tip.contains("打开端口成功")) {
//                initReadIdCard();
//            }else{
//                runOnUiThread(() -> ToastUtils.showShort(tip));
//            }
//        });
    }

    public ConstraintLayout getClRootView() {
        return mClRootView;
    }

    public ImageView getIvIcon() {
        return mIvIcon;
    }

    public TextView getDeptName() {
        return mTvDeptName;
    }

    public RecyclerView getRecyclerView() {
        return mRv;
    }

    public Badge getBadgeVehicleYw() {
        return mBadgeVehicleYw;
    }

    public Badge getBadgeVehicleMan() {
        return mBadgeVehicleMan;
    }

    public TextView getTvVehicleYw() {
        return mTvVehicleYw;
    }

    public TextView getTvVehicleMan() {
        return mTvVehicleMan;
    }


    /**
     * 初始化日期展示 年月日 周 时分秒
     * yyyy-MM-dd HH:mm:ss
     */
    private void initTime() {
        //每秒更新一次时间
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    Date date = new Date();
                    String year = TimeUtils.date2String(date, "yyyy");
                    String month = TimeUtils.date2String(date, "MM");
                    String day = TimeUtils.date2String(date, "dd");
                    String week = TimeUtils.getChineseWeek(date);
                    String time = TimeUtils.date2String(date, "HH:mm:ss");
                    final String finalTime = year + "年" + month + "月" + day + "日 " + getWeek(date);
                    mTvTime.setText(finalTime);
                });
            }
        };

        timer.schedule(timerTask, 0, 1000);
    }

    private String getWeek(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 EEEE");
        format = new SimpleDateFormat("EEEE");
        return format.format(date);
    }

    @SuppressLint({"NewApi", "NonConstantResourceId"})
    @Override
    public void onClick(View v) {
        final int viewId = v.getId();
        switch (viewId) {
            //机动车业务
            case R.id.tv_main_vehicle_yw:
                mainYwHandler.switchYwType(true, false, (String) v.getTag());
                break;
            //驾驶人业务
            case R.id.tv_main_vehicle_man_yw:
                mainYwHandler.switchYwType(false, true, (String) v.getTag());
                break;
            //检查版本更新
            case R.id.iv_main_yw_logo:
                UpdateUtil.checkUpdate(this, true);
                break;
            case R.id.tv_selected_yw_clear_all:
                mainYwHandler.clearAllYwTip();
                break;
            case R.id.bt_selected_yw_picknum:
                mainYwHandler.toJh(Contact.COMMON_WINDOW);
                break;
            case R.id.bt_selected_yw_vip_pick:
                mainYwHandler.toJh(Contact.VIP_WINDOW);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (audioReceiver != null) {
            unregisterReceiver(audioReceiver);
            audioReceiver = null;
        }
//        CardReader.getInstance(this).close();
//        UsbPrintManager.getInstance().closePrint();
        ServiceUtils.stopService(JhAudioService.class);
    }
}

